package com.p2l.letterblocks;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ActivityChapter extends Activity {
	private SwipeAdapter adapter;
	private ViewPager pager;
	private TextView left, right;
	private Context context;
	
	private SQLiteDatabase sqlite;
	private Database db;
	
	private ArrayList<Chapter> chapters;
	
	private String[] codes;
	
	private float size;
	private int userId;
	
	@Override
	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.chapter);
		context = this;
		
		codes = getResources().getStringArray(R.array.language_codes);
		size = getResources().getDimension(R.dimen.chapter);
		userId = getIntent().getIntExtra("userId", -1);
		
		left = (TextView) findViewById(R.id.lblArrowLeft);
		right = (TextView) findViewById(R.id.lblArrowRight);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		db = new Database(context);
		sqlite = db.getWritableDatabase();
		
		// get all chapters on the device
		String select = "SELECT DISTINCT TB_chapters.chapterId, TB_chapters.name, TB_chapters.price, TB_chapters.en, TB_chapters.es, TB_chapters.de, TB_chapters.dk";
		String join = " LEFT JOIN TB_chapter_transactions ON TB_chapters.chapterId = TB_chapter_transactions.chapterId";
		String where = (userId == -1 ? "" : " WHERE TB_chapters.price='0' OR TB_chapter_transactions.userId='" + userId + "'");
		Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_CHAPTERS, join, where);
		chapters = db.getChapters(cursor);
		
		//name.setText(chapters.get(0).getName());
		left.setBackgroundResource(android.R.color.transparent);
		
		adapter = new SwipeAdapter();
		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(adapter);
		pager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int state) { }
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				if (position == 0) {
					left.setBackgroundResource(android.R.color.transparent);
					right.setBackgroundResource(R.drawable.right_arrow);
				} else if (position == chapters.size() - 1) {
					left.setBackgroundResource(R.drawable.left_arrow);
					right.setBackgroundResource(android.R.color.transparent);
				} else {
					left.setBackgroundResource(R.drawable.left_arrow);
					right.setBackgroundResource(R.drawable.right_arrow);
				}
			}
			
			@Override
			public void onPageScrollStateChanged(int position) { }
		});
		
		select = null;
		where = null;
		join = null;
		cursor = null;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		db.close();
		db = null;
		sqlite = null;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (right.getBackground() != null)
			right.getBackground().setCallback(null);
		if (left.getBackground() != null)
			left.getBackground().setCallback(null);
		
		for (int i = 0; i < pager.getChildCount(); i++) {
			LinearLayout l = (LinearLayout) pager.getChildAt(i);
			if (l.getBackground() != null)
				l.getBackground().setCallback(null);
			
			TextView t = (TextView) l.getChildAt(0);
			if (t.getBackground() != null)
				t.getBackground().setCallback(null);
			l.removeAllViews();
		}
		pager.removeAllViews();
		chapters.clear();

		chapters = null;
		context = null;
		adapter = null;
		pager = null;
		right = null;
		codes = null;
		left = null;
		
		System.gc();
	}
	
	private class SwipeAdapter extends PagerAdapter {
		@Override
		public Object instantiateItem(ViewGroup collection, int position) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
			LinearLayout l = new LinearLayout(context);
			l.setOrientation(LinearLayout.VERTICAL);
			l.setLayoutParams(params);
			l.setGravity(Gravity.CENTER_HORIZONTAL);
			l.setTag(position);
			l.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, ActivityLevel.class);
					intent.putExtra("chapter", chapters.get((Integer)v.getTag()).getName());
					intent.putExtra("userId", userId);
					intent.putExtra("chapterId", chapters.get((Integer)v.getTag()).getId());
					intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
					context.startActivity(intent);
				}
			});

			BitmapDrawable picture = null;
			String name = chapters.get(position).getName() + "_picture";
			BitmapFactory.Options options = new BitmapFactory.Options();
			try {
				int id = getResources().getIdentifier(name, "drawable", getPackageName());
				if (id == 0) {
					throw new Resources.NotFoundException("id = 0");
				} else{
					options.inScaled = false;
					picture = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), id, options));
				}
			} catch (Resources.NotFoundException e) {
				Bitmap b = Server.loadBitmap(context, Server.FOLDERS[5], name + ".png");
				if (b == null) {
					String url = Server.URL_HOME + Server.FOLDERS[5] + chapters.get(position).getName() + "_picture.png";
					new DownloadBitmapTask().execute(url, chapters.get(position).getName());
					picture = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.picture_not_found, options));
				} else {
					picture = new BitmapDrawable(b);
				}
			}
			l.setBackgroundDrawable(picture);
			
			String language = Locale.getDefault().getLanguage();
			boolean found = false;
			int i = 0;
			
			while (!found && i < codes.length) {
				if (codes[i].equals(language))
					found = true;
				else
					i++;
			}
			
			if (!found)
				i = 0;
			
			TextView t = new TextView(context);
			t.setText(chapters.get(position).getDescription()[i]);
			t.setBackgroundResource(R.drawable.bar_chapter_level);
			t.setTextColor(Color.BLACK);
			t.setTextSize(size);
			t.setTypeface(Typeface.DEFAULT_BOLD);
			t.setGravity(Gravity.CENTER);
			
			l.addView(t);
			collection.addView(l);
			
			return l;
		}
		
		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			LinearLayout l = (LinearLayout) view;
			if (l != null)
				if (l.getBackground() != null);
					l.getBackground().setCallback(null);
			
			TextView t = (TextView) l.getChildAt(0);
			if (t.getBackground() != null)
				t.getBackground().setCallback(null);
			l.removeAllViews();
				
			collection.removeView(l);
		}
		
		@Override
		public int getCount() {
			return chapters.size();
		}

		@Override
		public boolean isViewFromObject(View v, Object o) {
			return v == o;
		}
		
	}
	
	private class DownloadBitmapTask extends AsyncTask<String, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(String... params) {
    		try {
				InputStream in = Server.open(params[0]);
				Bitmap picture = Server.downloadBitmap(in);
				String folder = Server.FOLDERS[5];
				String name = params[1].replace(" ", "_");
				Server.saveBitmap(context, folder, name.toLowerCase() + "_picture.png", picture);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
				return false;
			}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	this.cancel(true);
	    }
	}
}
